<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.name" placeholder="姓名"></el-input>
          <el-button
            type="primary"
            round
            icon="el-icon-search"
            @click="getOrganizerList"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right">
          <el-button
            @click="openEditUI(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="organizerList" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="id"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.status)" effect="dark">
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="组织名"
          width="250"
          align="center"
        ></el-table-column>
        <el-table-column prop="pic" label="头像" width="100" align="center">
          <template slot-scope="scope">
            <img
              :src="scope.row.pic || defaultAvatar"
              @error="handleError"
              alt="头像"
              style="width: 50px; height: 50px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人姓名"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="contactPhone"
          label="联系人电话"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="contactEmail"
          label="联系人邮箱"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="openEditUI(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
              <el-button
                @click="deleteOrganizer(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="clearForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="organizerForm" ref="organizerFormRef" :rules="rules">
        <el-form-item
          v-if="organizerForm.id == null || organizerForm.id == undefined"
          label="账号"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="organizerForm.id == null || organizerForm.id == undefined"
          label="密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="组织名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="organizerForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="http://localhost:8088/files"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">上传图片</el-button>
          </el-upload>
          <img
            v-if="pic"
            :src="pic"
            alt="uploaded image"
            style="width: 100px; height: 100px; margin-top: 10px"
          />
        </el-form-item>
        <el-form-item
          label="联系人姓名"
          prop="contactName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.contactName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系人电话"
          prop="contactPhone"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.contactPhone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系人邮箱"
          prop="contactEmail"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.contactEmail"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="组织简介"
          prop="description"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="organizerForm.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAndDelete">取 消</el-button>
        <el-button type="primary" @click="saveOrganizer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import organizerApi from "@/api/organizerManage";
import { formatDate } from "@/utils/dateFormat";
export default {
  data() {
    return {
      defaultAvatar: require("@/assets/default.jpeg"),
      formLabelWidth: "130px",
      newAvatarUrl: "",
      oldAvatarUrl: "",
      organizerForm: {
        email: "",
        status: "",
        password: "",
        name: "",
        contactPhone: "",
        pic: "",
      },
      pic: "",
      dialogFormVisible: false,
      title: "新增组织者",
      organizerList: [],
      searchModel: {
        name: "",
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        name: [{ required: true, message: "请输入组织名", trigger: "blur" }],
        contactName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入联系人电话", trigger: "blur" },
        ],
        contactEmail: [
          { required: true, message: "请输入联系人邮箱", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getOrganizerList();
  },
  methods: {
    getOrganizerList() {
      organizerApi.getOrganizerList(this.searchModel).then((response) => {
        console.log(response);
        this.organizerList = response.data.list;
        this.total = response.data.total;
      });
    },
    statusType(status) {
      return status === "ACTIVE" ?   "danger" : "success";
    },
    statusText(status) {
      return status === "ACTIVE" ?   "禁用" : "活跃";
    },
    handleSizeChange(val) {
      this.searchModel.pageSize = val;
      this.getOrganizerList();
    },
    handleCurrentChange(val) {
      this.searchModel.pageNo = val;
      this.getOrganizerList();
    },
    handleError(event) {
      event.target.src = this.defaultAvatar;
    },
    openEditUI(id) {
      if (id == null) {
        this.title = "新增组织者";
        this.organizerForm = {};
        this.pic = "";
        this.newAvatarUrl = "";
      } else {
        this.title = "修改组织者";
        organizerApi.getOrganizerById(id).then((response) => {
          this.organizerForm = response.data;
          this.pic = response.data.pic;
        });
      }
      this.dialogFormVisible = true;
    },
    saveOrganizer() {
      this.$refs.organizerFormRef.validate((valid) => {
        if (valid) {
          // 判断是否需要删除旧头像
          if (
            this.oldAvatarUrl &&
            this.oldAvatarUrl !== this.organizerForm.pic
          ) {
            console.log("Deleting old avatar:", this.oldAvatarUrl);
            this.deleteOldAvatar(this.oldAvatarUrl); // 删除旧头像
          }
          this.submitOrganizer(); // 提交组织者信息
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deleteOldAvatar(oldAvatarUrl) {
      if (oldAvatarUrl) {
        // 检查传入的旧头像 URL
        const fileName = oldAvatarUrl.split("/").pop(); // 使用旧头像的 URL 获取文件名
        organizerApi
          .deleteImage(fileName)
          .then(() => {
            console.log("Old avatar deleted successfully:", oldAvatarUrl);
          })
          .catch((error) => {
            console.error("删除旧头像失败", error);
          });
      } else {
        console.log("No old avatar to delete.");
      }
    },
    submitOrganizer() {
      this.organizerForm.pic = this.pic; // 存入表单数据中
      // 提交给后台
      organizerApi.saveOrganizer(this.organizerForm).then((response) => {
        this.$message({
          message: response.message,
          type: "success",
        });
        // 关闭对话框
        this.dialogFormVisible = false;
        // 刷新表格
        this.getOrganizerList();
      });
    },
    deleteOrganizer(organizer) {
      this.$confirm(`您确认删除组织 ${organizer.name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          organizerApi.deleteOrganizerById(organizer.id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getOrganizerList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
      }
      return isImage;
    },
    handleUploadSuccess(response) {
      this.oldAvatarUrl = this.organizerForm.pic;
      console.log(response);
      this.organizerForm.pic = response.data;
      this.newAvatarUrl = response.data;
      this.pic = response.data;
    },
    cancelAndDelete() {
      if (!this.organizerForm.id && this.newAvatarUrl) {
        // **新增：新增组织者且上传了头像的情况下，取消时删除新头像**
        const fileName = this.newAvatarUrl.split("/").pop();
        organizerApi.deleteImage(fileName).catch((error) => {
          console.error("取消操作时删除新头像失败", error);
        });
      }
      this.dialogFormVisible = false;
      this.clearForm(); // 清除表单数据
    },
    clearForm() {
      this.organizerForm = {};
      this.newAvatarUrl = ""; // **更改：清空新头像URL**
      this.$refs.organizerFormRef.clearValidate();
    },
  },
};
</script>

<style>
#search {
  margin-bottom: 10px;
}
</style>